package com.werewolf;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.content.Context;
import android.content.res.Resources;

public class XMLFunctions
{
	private String XMLString;
	
	private Document XMLData;
	
	public XMLFunctions(Context context, int resID)
	{
		
		try {
			Resources res = context.getResources();
			InputStream inStream = res.openRawResource(resID);
			byte [] readByte = new byte[inStream.available()];
			inStream.read(readByte);
			XMLString = new String(readByte);

		} 
		catch (IOException e)
		{
			System.out.println("Could not read file" + e.getMessage());

		}
		
	}
	

	public Document XMLData()
	{
		Document Doc = null;

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

		try
		{
			DocumentBuilder db = dbf.newDocumentBuilder();
			InputSource inSource = new InputSource();
			inSource.setCharacterStream(new StringReader(XMLString));
			Doc = db.parse(inSource);
		}
		catch(ParserConfigurationException e)
		{
			System.out.println( "XML Parse Error" +e.getMessage());
		} 
		catch (SAXException e)
		{
			// TODO Auto-generated catch block
			System.out.println( "" +e.getMessage());
		}
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			System.out.println( "" +e.getMessage());
		}

		return Doc;

	}

	public String XMLBlob()
	{
		return XMLString;
	}

	int numResults(Document doc)
	{		
		NodeList nl = doc.getChildNodes();
		return nl.getLength();
	}

	final static String getElementValue(Node element)
	{
		Node child;
		String ret = "";
		if(element != null)
		{
			if(element.hasChildNodes() )
			{
				child = element.getFirstChild();
				while(  child != null )
				{
					if(child.getNodeType() == Node.TEXT_NODE)
					{
						ret = child.getNodeValue();
						child = null;
					}
					else
					{
						child.getNextSibling();
					}
				}

			}
		}
		return ret;
	}

	String getValue(Element item, String str)
	{
		NodeList n = item.getElementsByTagName(str);
		return getElementValue(n.item(0));
	}

	
	Document getDocument()
	{
		return XMLData;
		
	}

}
